/**
 * 触发服务
 */

//引入Q模块
let Q = require('q');

//target入口函数
let index = function(getData, postData, config, _redis, db, wsServer) {
	let deferred = Q.defer();
	if(postData.storeId && postData.funId && postData.tableNum) {
		getServiceSum(wsServer.clients, postData.storeId, postData.tableNum).then(function(serviceSum) {
			if(serviceSum > 0) {
				deferred.resolve(['broadcast', {
					storeId: postData.storeId,
					type: 'user',
					event: 'storeFun',
					data: {
						funId: postData.funId,
						tableNum: postData.tableNum,
						timestamp: Date.now()
					}
				}]);
			}
			else {
				db.insert('noReceiveFunLogs', {
					funId: postData.funId,
					tableNum: postData.tableNum,
					timestamp: Date.now()
				}).then(function() {
					deferred.resolve(-1);
				}, function() {
					//记录未读服务通知时出错
					deferred.reject('-0099');
				});
			}
		}, function() {
			//获取客服个数失败
			deferred.reject('-0098');
		});
	}
	else {
		//服务消息接口参数不足
		deferred.reject('-0097');
	}
	return deferred.promise;	
}

//获取对应商户的在线客服数量
var getServiceSum = function(clients, storeId, tableNum) {
	var deferred = Q.defer();
	//尝试计数客服连接数量
	try {
		if(clients.size == 0) {
			deferred.resolve(0);
		}
		//客服总数变量
		var sum = 0;
		var index = 0;
		//遍历连接端
		clients.forEach(function(client) {
			//如果属于该商店的连接则为总数+1
			if(client.storeId == storeId) {
				if(client.tableNums != '*') {
					for(let tableNumIndex in client.tableNums) {
						if(client.tableNums[tableNumIndex] == tableNum) {
							sum++;
							break;
						}
					}
				}
				else {
					sum++;
				}
			}
			//判断是否执行完成
			if(++index == clients.size) {
				//返回总数
				deferred.resolve(sum);
			}
		});
	}
	catch(e) {
		//尝试失败直接返回0位客服在线
		deferred.resolve(0);
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};

